from django.db.models.loading import get_model
from django.http import Http404
from django.views.generic.list_detail import object_list

from tppt.lib import utils


def perform_action(request, action_name, **kwargs):
	from tppt.lib.actions import get_action 
	from tppt.lib.actions.url import get_object_from_specification 
	from tppt.lib import exceptions
	
	params=kwargs

	get_params=utils.simplify_query_dict(request.GET)
	params.update(get_params)

	try:
		object=get_object_from_specification(params)
		action=get_action(object, action_name)
#	except exceptions.MissingActionError:
#		raise Http404('Invalid action name: %s' % action_name)
	except exceptions.MissingModelError, model:
		raise Http404('Invalid model name: %s' % model)

	action.assign_request(request)	
	action.add_params(params)	
	return action.perform() 

def generic_list(request, model_name, template_name=None, **kwargs):
	from tppt.lib.utils import template_exists
	
	model=get_model('data', model_name)
	if not model:
		raise Http404('Model not found: "%s"' % model_name)
	queryset=model.objects.all()
	if not template_name:
		tn_def='%s/%s_list.html' % (model._meta.app_label, model.__name__)
		if template_exists(tn_def):
			template_name=tn_def
		else:
			template_name='%s/generic_list.html' % model._meta.app_label
	ec={}  #extra_context
	if model._meta.admin.list_display!=['__str__']:
		ec['columns']=model._meta.admin.list_display
	return object_list(request, queryset, template_name=template_name, extra_context=ec, **kwargs) 